import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
import { Icon, SearchBar } from 'react-native-elements';
import OrderList from './components/OrderList';
import { Calendar } from 'react-native-calendars';
import moment from 'moment';
import { primaryColor, screenWidth, toast } from './utils';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  header: {
    flexDirection: 'row',
    backgroundColor: '#e1e8ee'
  },
  search: {
    width: screenWidth*3/10,
  },
  date: {
    width: screenWidth*3/10,
  },
  statistic: {
    width: screenWidth*4/10,
    flexDirection: 'row'
  },
  button: {
    paddingVertical: 16,
    paddingHorizontal: 8
  },
  buttonSelect: {
    paddingVertical: 16,
    paddingHorizontal: 8,
    backgroundColor: primaryColor,
  },
  dateText: {
    color: primaryColor
  }
});

class HistoryPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `History`,
      tabBarLabel: `History`,
      tabBarIcon: ({tintColor}) => <Icon name='history' type='font-awesome' color={tintColor} size={24}/>,
      headerRight: (
        <TouchableOpacity onPress={() => navigation.navigate('BagScan', {assignOrder: true})}>
          <Icon style={{marginRight: 16}} name='add' color={primaryColor}/>
        </TouchableOpacity>
      ),
    };
  }
  state = { date: new Date().toString(), calendarOpen: false, filter: 'location' }
  onToggleCalendar = () => this.setState({calendarOpen: !this.state.calendarOpen})
  onSearchChange = (search) => {
    this.setState({search:search||null, searching: true});
    setTimeout(() => this.setState({searching: false}), 2000);
  }
  onMonthChange = (date) => this.onSelectDate(date, true)
  onSelectDate = ({year, month, day, hour=0}, calendarOpen=false) => {
    const date = moment([year, month-1, day, hour]).toDate().toString();
    this.setState({
      date,
      calendarOpen
    });
    this.props.refetch({date});
  }
  onSelectOrder = (order) => {
    this.props.navigation.navigate('OrderDetail', {displayId: order.displayId, id: order.id});
  }
  onFilterPickup = () => {
    this.setState({filter: 'pickup'});
    toast('Only show pickup orders');
  }
  onFilterDelivery = () => {
    this.setState({filter: 'delivery'});
    toast('Only show delivery orders');
  }
  onFilterLocation = () => {
    this.setState({filter: 'location'});
    toast('Show all orders'); 
  }
  onUpdateCount = (pickupCount, deliveryCount, locationCount) => this.setState({pickupCount, deliveryCount, locationCount})
  render() {
    const date = moment(this.state.date);
    const select = date.format('YYYY-MM-DD');
    const { pickupCount, deliveryCount, locationCount, filter, search } = this.state;

    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={styles.search}>
            <SearchBar inputStyle={{height:50}} keyboardType='numeric' lightTheme round showLoadingIcon={this.state.searching}
              onChangeText={this.onSearchChange} value={this.state.search} placeholder={this.props.chinese?'查询':'Search'}/>
          </View>
          <View style={styles.date}>
            <TouchableOpacity style={styles.button} onPress={this.onToggleCalendar}>
              <Text style={styles.dateText}>{date.format('MMM Do YYYY')}</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.statistic}>
            <TouchableOpacity style={filter==='pickup'?styles.buttonSelect:styles.button} onPress={this.onFilterPickup}>
              <Text>{`P ${pickupCount||0}`}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={filter==='delivery'?styles.buttonSelect:styles.button} onPress={this.onFilterDelivery}>
              <Text>{`D ${deliveryCount||0}`}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={filter==='location'?styles.buttonSelect:styles.button} onPress={this.onFilterLocation}>
              <Text>{`L ${locationCount||0}`}</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.container}>
          {this.state.calendarOpen?
            <Calendar current={select} hideExtraDays selected={[select]} theme={{
              selectedDayBackgroundColor: primaryColor,
              todayTextColor: primaryColor,
              dotColor: primaryColor,
              arrowColor: primaryColor,}}
              onDayPress={this.onSelectDate} markedDates={this.props.markedDates}
              onMonthChange={this.onMonthChange} displayLoadingIndicator={this.props.loading}/>
            :<OrderList onSelect={this.onSelectOrder} onDateChagne={this.onDateChagne}
              date={this.state.date} onUpdateCount={this.onUpdateCount} filter={filter}
              search={search} history/>
          }
        </View>
      </View>
    );
  }
}

export default graphql(gql`
  query HistoryPage($date:String!,$history:Boolean) {
    workingDays(date:$date,history:$history)
  }
`, {
  options: () => {
    return {
      variables: {
        date: new Date().toString(),
        history: true
      }
    }
  },
  props: ({data:{workingDays, refetch, loading}}) => {
    let markedDates = {};
    if (workingDays) {
      workingDays.map(date => {
        markedDates[moment(date).format('YYYY-MM-DD')] = {marked: true};
      });
    }

    return {
      markedDates,
      refetch,
      loading
    };
  }
})(HistoryPage);

